<?php

namespace App\Http\Controllers;

use App\Models\Download;
use Illuminate\Http\Request;

class DownloadController extends Controller
{
    //

    public function index(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');
        $user_id = $request->get('userId');
        $author_id = $request->get('authorId');

        if ($author_id){
            $lists = Download::query()->where('author_id', $author_id)
                ->where('state',1)
                ->orderByDesc('created_at')
                ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
        }else{
            $lists = Download::query()->where('user_id', $user_id)
                ->where('state',1)
                ->orderByDesc('created_at')
                ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
        }

        return $this->response($lists);
    }

    public function store(Request $request)
    {
        $user = $request->user();
        $cover_id = $request->post('coverId');
        $index = $request->post('index');

        $download = (new Download)->downloadByCoverId($user->id, $cover_id, $index);

        if ($download) return $this->response([],'下载成功');
        else return $this->response([],'下载失败', 500);
    }

    public function count()
    {
        $count = Download::query()->count();
        return $this->response(['count' => $count]);
    }
}
